﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WebInfoExtractor
{
    public partial class Form1 : Form
    {
        private readonly HttpClient _httpClient = new HttpClient();

        public Form1()
        {
            InitializeComponent();
            InitializeRegex();
        }

        private Regex _phoneRegex;
        private Regex _emailRegex;

        private void InitializeRegex()
        {
            // 手机号码正则：1开头，第二位3-9，后面9位数字（考虑单词边界避免部分匹配）
            _phoneRegex = new Regex(@"\b1[3-9]\d{9}\b", RegexOptions.Compiled | RegexOptions.ExplicitCapture);

            // 邮箱正则：常见格式匹配（非严格RFC标准，适合提取场景）
            _emailRegex = new Regex(@"\b[\w\.-]+@[\w\.-]+\.\w+\b", RegexOptions.Compiled | RegexOptions.ExplicitCapture);
        }

        private async void btnFetch_Click(object sender, EventArgs e)
        {
            btnFetch.Enabled = false;
            lstPhones.Items.Clear();
            lstEmails.Items.Clear();
            try
            {
                string url = txtUrl.Text.Trim();
                if (!Uri.IsWellFormedUriString(url, UriKind.Absolute))
                {
                    MessageBox.Show("请输入有效的URL地址", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                string content = await GetPageContentAsync(url);
                string plainText = RemoveHtmlTags(content);

                // 提取手机号码
                var phones = _phoneRegex.Matches(plainText)
                                       .Cast<Match>()
                                       .Select(m => m.Value)
                                       .Distinct();
                lstPhones.Items.AddRange(phones.ToArray());

                // 提取邮箱
                var emails = _emailRegex.Matches(plainText)
                                       .Cast<Match>()
                                       .Select(m => m.Value)
                                       .Distinct();
                lstEmails.Items.AddRange(emails.ToArray());
            }
            catch (HttpRequestException ex) when (ex.StatusCode == System.Net.HttpStatusCode.NotFound)
            {
                MessageBox.Show("页面未找到", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"获取内容失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                btnFetch.Enabled = true;
            }
        }

        private async Task<string> GetPageContentAsync(string url)
        {
            using var response = await _httpClient.GetAsync(url);
            response.EnsureSuccessStatusCode();
            return await response.Content.ReadAsStringAsync();
        }

        private string RemoveHtmlTags(string html)
        {
            // 去除HTML标签并简化空白字符
            return Regex.Replace(html, "<.*?>", string.Empty, RegexOptions.Singleline)
                       .Replace("\r\n", " ")
                       .Replace("\n", " ")
                       .Replace("\t", " ")
                       .Trim();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // 设置用户代理模拟浏览器（避免某些网站拒绝请求）
            _httpClient.DefaultRequestHeaders.UserAgent.ParseAdd("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36");
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            txtUrl.Clear();
            lstPhones.Items.Clear();
            lstEmails.Items.Clear();
        }

        #region 界面设计部分（需通过设计器创建以下控件）
        // 以下代码需在Form设计器中手动创建对应控件并设置属性：
        // 1. 文本框 txtUrl 用于输入URL
        // 2. 按钮 btnFetch 用于触发获取（Text="获取内容"）
        // 3. 按钮 btnClear 用于清空结果（Text="清空结果"）
        // 4. 列表框 lstPhones 用于显示手机号码
        // 5. 列表框 lstEmails 用于显示邮箱
        // 6. 标签等辅助控件
        #endregion
    }
}
